﻿using System;
using System.Collections.Generic;
using System.Linq;
using Com.PhilChuang.Mobile.Apps.LocationSender.Ui.Views.Impl.Pages;
using Com.PhilChuang.Mobile.Apps.LocationSender.Ui.Views.Impl.ViewModels;

namespace Com.PhilChuang.Mobile.Apps.LocationSender.Ui.Views.Impl.ViewFacades
{
	public class SettingsViewFacade : AbstractLocationSenderAppViewFacade<SettingsPage, SettingsPageViewModel>, ISettingsView
	{
		#region Events
		public event Action DoDisableLocationServices = delegate { };
		#endregion

		#region Instance Variables (EMPTY)
		#endregion

		#region Properties (EMPTY)
		#endregion

		#region Constructors
		public SettingsViewFacade ()
		{
			Init (false);
		}

		public SettingsViewFacade (SettingsPage page)
		{
			myPage = page;
			Init (true);
		}

		private void Init (bool wireUp)
		{
			myViewModel = new SettingsPageViewModel ();
			myViewModel.IsAssociatedWithViewFacadeAndPage = true;
			myViewModel.HasBeenLoaded = false;
			myViewModel.ReportAnalyticsData = AppSettings.RiOptIn;
			if (wireUp) WireUpPage ();
		}
		#endregion

		#region Implementation of IView/ISettingsView
		// no methods to implement
		#endregion

		/// <summary>
		/// Unsubscribes view event handlers.
		/// Call base impl as last step.
		/// </summary>
		protected override void UnWirePage ()
		{
			if (myPage == null) return;

			// ISettingsView
			myPage.DoDisableLocationServices -= FireDoDisableLocationServices;

			if (myViewModel != null)
				myViewModel.PropertyChanged -= OnViewModelPropertyChanged;

			base.UnWirePage ();
		}

		/// <summary>
		/// Subscribes view event handlers.
		/// Call base impl as first step.
		/// </summary>
		protected override void WireUpPage ()
		{
			if (myPage == null) return;

			base.WireUpPage ();

			// ISettingsView
			myPage.DoDisableLocationServices += FireDoDisableLocationServices;

			if (myViewModel != null)
				myViewModel.PropertyChanged += OnViewModelPropertyChanged;
		}

		protected void FireDoDisableLocationServices ()
		{ DoDisableLocationServices (); }

		private void OnViewModelPropertyChanged (object sender, System.ComponentModel.PropertyChangedEventArgs e)
		{
			//if (e.PropertyName == INPCHelper.GetPropertyName (() => myViewModel.ReportAnalyticsData)) // don't why this throws VerificationException
			if (e.PropertyName == "ReportAnalyticsData")
			{
				AppSettings.RiOptIn = myViewModel.ReportAnalyticsData;
			}
		}
	}
}
